
package com.omt.esouk.util;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;

import org.apache.log4j.Logger;
import org.omnifaces.eventlistener.DefaultPhaseListener;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;

import com.omt.esouk.web.util.LogPhaseListener;

public class LoginErrorPhaseListener extends DefaultPhaseListener {

	private static final long serialVersionUID = 1L;

	private static final Logger log = Logger.getLogger(LogPhaseListener.class);

	@Override
	public void beforePhase(final PhaseEvent arg0) {

		Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
		                .get(WebAttributes.AUTHENTICATION_EXCEPTION);

		if (e instanceof BadCredentialsException) {
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
			                .put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
			FacesContext.getCurrentInstance()
			                .addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid username or password", null));
		}
	}

	public LoginErrorPhaseListener() {

		super(PhaseId.ANY_PHASE);
	}

	@Override
	public void afterPhase(PhaseEvent event) {

		if (log.isDebugEnabled()) {
			log.debug(event.getPhaseId());
		}
	}

}
